/**
 * 进货入库管理初始化
 */
var Purchase = {
    id: "PurchaseTable",	//表格id
    purchaseData: {},
    seItem: null,		//选中的条目
    table: null,
    subPage: null,
    totalPrice: 0, //计算出的总金额
    layerIndex: -1
};

/**
 * 初始化订单表格的列
 */
Purchase.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
        {title: '商品id', field: 'id', visible: false, align: 'center', valign: 'middle'},
        {title: '进货数量', field: 'goodsNum', visible: true, align: 'center', valign: 'middle'},
        {title: '商品编码', field: 'goodsCode', visible: true, align: 'center', valign: 'middle'},
        {title: '商品名称', field: 'goodsName', visible: true, align: 'center', valign: 'middle'},
        {title: '商品型号', field: 'goodsModel', visible: true, align: 'center', valign: 'middle'},
        {title: '商品单位', field: 'goodsUnit', visible: true, align: 'center', valign: 'middle'},
        {title: '采购价', field: 'goodsPurchasePrice', visible: true, align: 'center', valign: 'middle'},
        {title: '出售价格', field: 'goodsSellingPrice', visible: false, align: 'center', valign: 'middle'},
        {title: '库存数量', field: 'goodsInventoryQuantity', visible: true, align: 'center', valign: 'middle'},
        {title: '库存下限', field: 'goodsMinNum', visible: false, align: 'center', valign: 'middle'},
        {title: '上次采购价格', field: 'goodsLastPurchasePrice', visible: false, align: 'center', valign: 'middle'},
        {title: '创建者', field: 'createBy', visible: false, align: 'center', valign: 'middle'},
        {title: '创建时间', field: 'createDate', visible: false, align: 'center', valign: 'middle'},
        {title: '更新者', field: 'updateBy', visible: false, align: 'center', valign: 'middle'},
        {title: '更新时间', field: 'updateDate', visible: false, align: 'center', valign: 'middle'},
        {title: '备注信息', field: 'remarks', visible: false, align: 'center', valign: 'middle'},
        {title: '删除标记（0：正常；1：删除）', field: 'delFlag', visible: false, align: 'center', valign: 'middle'},
        {title: '供应商名称', field: 'supplierId', visible: false, align: 'center', valign: 'middle'},
        {title: '商品分类id', field: 'goodsCategoryId', visible: false, align: 'center', valign: 'middle'}
    ];
};

/**
 * 初始化订单内的 商品列表表格
 */
Purchase.initListGoodsTable = function () {
    return [
        {field: 'selectItem', radio: true},
        {title: '主键', field: 'goodsId', visible: true, align: 'center', valign: 'middle'},
        {title: '商品编码', field: 'goodsCode', visible: true, align: 'center', valign: 'middle'},
        {title: '商品型号', field: 'goodsModel', visible: true, align: 'center', valign: 'middle'},
        {title: '商品名称', field: 'goodsName', visible: true, align: 'center', valign: 'middle'},
        {title: '购进商品数量', field: 'goodsNum', visible: true, align: 'center', valign: 'middle'},
        {title: '采购价', field: 'unitPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '进货总价', field: 'totalPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '商品单位', field: 'goodsUnit', visible: true, align: 'center', valign: 'middle'},
        {title: '订单ID', field: 'purchaseId', visible: false, align: 'center', valign: 'middle'},
        {title: '商品分类id', field: 'goodsCategoryId', visible: false, align: 'center', valign: 'middle'},
        {title: '创建者', field: 'createBy', visible: false, align: 'center', valign: 'middle'},
        {title: '创建时间', field: 'createDate', visible: false, align: 'center', valign: 'middle'},
        {title: '更新者', field: 'updateBy', visible: false, align: 'center', valign: 'middle'},
        {title: '更新时间', field: 'updateDate', visible: false, align: 'center', valign: 'middle'},
        {title: '备注信息', field: 'remarks', visible: false, align: 'center', valign: 'middle'},
        {title: '删除标记（0：正常；1：删除）', field: 'delFlag', visible: false, align: 'center', valign: 'middle'}
    ];
}


/**
 * 清除数据
 */
Purchase.clearData = function () {
    this.purchaseData = {};
}
/**
 * 清除dom显示数据
 */
Purchase.clearDom = function () {
    this
        .setDomVal('id')
        .setDomVal('amountPaid')
        .setDomVal('amountPayable')
        .setDomVal('orderNumber')
        .setDomVal('state')
        .setDomVal('createBy')
        .setDomVal('createDate')
        .setDomVal('updateBy')
        .setDomVal('updateDate')
        .setDomVal('remarks')
        .setDomVal('delFlag')
        .setDomVal('supplierId');
}

/**
 * 收集数据
 */
Purchase.collectData = function () {
    this
        .set('id')
        .set('amountPaid')
        .set('amountPayable')
        .set('orderNumber')
        .set('state')
        .set('createBy')
        .set('createDate')
        .set('updateBy')
        .set('updateDate')
        .set('remarks')
        .set('delFlag')
        .set('supplierId');
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
Purchase.set = function (key, val) {
    this.purchaseData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置dom中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
Purchase.setDomVal = function (key, val) {
    (typeof val === "undefined") ? $("#" + key).val('') : $("#" + key).val(val);
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
Purchase.get = function (key) {
    return $("#" + key).val();
}


/**
 * 检查是否选中
 */
Purchase.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length === 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        Purchase.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加进货入库
 */
Purchase.openAddPurchase = function () {
    var index = layer.open({
        type: 2,
        title: '添加进货入库',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/purchase/purchase_add'
    });
    this.layerIndex = index;
};

/**
 * 删除进货入库
 */
Purchase.delete = function () {
    if (this.check()) {
        var selected = this.table.btInstance.bootstrapTable('getSelections');
        console.log(selected[0].id);
        this.table.btInstance.bootstrapTable('removeByUniqueId',selected[0].id);
    }
};

/**
 * 查询供应商
 */
Purchase.selectSupplier = function () {
    //查找供应商下拉框
    var ajax = new $ax(Feng.ctxPath + "/managerSupplier/list", function (data) {
        $.each(data, function (index, supplier) {
            var supplierId = supplier['id'];
            var supplierName = supplier['supplierName'];
            $("#supplierId").html("<option value='" + supplierId + "'>" + supplierName + "</option>");
        })
    }, function (data) {
        Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
    });
    ajax.start();
}

/**
 * 是否支付下拉框
 */
Purchase.isPaySelect = function () {
    $("#state").html("<option value='1'>已支付</option>" +
        "<option value='0'>未支付</option>")
}


/**
 * 保存前检查数据
 */
Purchase.checkData = function () {
    var data = Purchase.table.btInstance.bootstrapTable('getData', true);

    if ('' === data || typeof data === 'undefined' || data.length === 0) {
        Feng.info('请先添加商品！');
        return false;
    }

    var supplier = $("#supplierId option:selected").val();
    if ('' === supplier || typeof supplier === 'undefined') {
        Feng.info("请选择供应商！");
        return false;
    }

    var amountPaid = $("#amountPaid").val();
    if ('' === amountPaid || typeof amountPaid === 'undefined') {
        Feng.info('请输入实付金额!');
        return false;
    }

    var amountPayable = $("#amountPayable").val();
    if ('' === amountPayable || typeof amountPayable === 'undefined') {
        Feng.info("请输入应付金额!");
        return false;
    }

    var createDate = $("#createDate").val();
    if('' === createDate || typeof createDate === 'undefined'){
        Feng.info("请选择订单日期!");
        return false;
    }

    var state = $("#state option:selected").val();
    if ('' === state || typeof state === 'undefined') {
        Feng.info("请选择是否支付!");
        return false;
    }

    var orderNumber = $("#orderNumber").text();
    if ('' === orderNumber || typeof orderNumber === 'undefined') {
        Feng.info("订单号为空，请刷新页面重新提交!");
        return false;
    }

    return true;
}

/**
 * 订单保存
 */
Purchase.save = function () {
    if (this.checkData()) {
        //清除数据
        this.clearData();
        //获取form数据
        this.collectData();
        var ajax = new $ax(Feng.ctxPath + "/purchase/add", function (data) {
            Feng.success(data.message);
            //清除表单
            Purchase.clearData();
            //清除dom数据显示
            Purchase.clearDom();
            //清除表格数据
            Purchase.table.btInstance.bootstrapTable('removeAll');
            //输出
            console.log('新单号：', data.result);
            //重新赋值单号
            $("#orderNumber").text(data.result);
        }, function (data) {
            Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
        });
        //获取单据号码
        this.purchaseData['orderNumber'] = $('#orderNumber').text();
        //获取添加的表格数据
        this.purchaseData['purchaseGoodsList'] = this.table.btInstance.bootstrapTable('getData', true);
        //请求数据
        var requestData = JSON.stringify(this.purchaseData);
        console.log("请求数据->", requestData);
        //设置为请求数据为json类型
        ajax.setContentType('application/json');
        ajax.setData(requestData);
        ajax.start();
    }
}

/**
 * 选中商品后计算出价格并赋值
 */
Purchase.calculateTotalPrice = function (cTotalPrice) {
    var cAmountPaid = $("#amountPaid").val();
    var cAmountPayable = $("#amountPayable").val();
    if (cAmountPaid === '' || cAmountPayable === '') {
        $("#amountPaid").val(cTotalPrice);
        $("#amountPayable").val(cTotalPrice);
    } else {
        var amountPaid = parseFloat(cAmountPaid);
        var amountPayable = parseFloat(cAmountPayable);
        //累加价格
        $("#amountPaid").val(cTotalPrice + amountPaid);
        $("#amountPayable").val(cTotalPrice + amountPayable);
    }
}

$(function () {
    var defaultColunms = Purchase.initListGoodsTable();
    var table = new BSTable(Purchase.id, "", defaultColunms);
    table.setUniqueId('goodsId');
    Purchase.table = table.init();

    //初始化下拉框
    Purchase.selectSupplier();
    Purchase.isPaySelect();
});
